from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.hashers import check_password
from .models import User
import re


class MyModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            if re.match(r'^1[345789]\d{9}$', username):
                users = User.objects.get(mobile=username)
            else:
                users = User.objects.get(username=username)
        except:
            return None
        if check_password(password, users.password) == False:
            return None
        return users
